package com.feisi.controller;

import com.feisi.domain.User;
import com.feisi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin.action")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录验证
     *
     * @param request
     * @return
     */
    @RequestMapping("/loginVerification")
    public @ResponseBody
    Map<String, Object> login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        Map<String, Object> map = new HashMap<>();
        List<User> users = userService.findByNameAndPassword(username, password);
        System.out.println(users.size());
        //是否登录成功
        //失败
        if (users.size() == 0) {
            System.out.println("=======");
            map.put("msg", "登录失败");
        } else {//成功
            request.getSession().setAttribute("loginuser", users.get(0));
            request.getSession().setAttribute("userid", users.get(0).getId());
            request.getSession().setAttribute("username", users.get(0).getU_name());
            map.put("msg", "登录成功");
//            map.put("userid", users.get(0).getId());
//            map.put("username", users.get(0).getU_name());
        }
        return map;
    }

    /**
     * 返回登陆者信息
     * @param request
     * @return
     */
    @RequestMapping("/getUsername")
    public @ResponseBody
    Map<String, Object> getUsername(HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("username");
        Integer userid = (Integer) request.getSession().getAttribute("userid");
        Map<String,Object> map = new HashMap();
        map.put("userid",userid );
        map.put("username", username);
        return map;
    }


}
